﻿using Infrastructure.Utils.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Infrastructure.Utils
{
    public class AssemblyLoaderProxy : IAssemblyLoader
    {
        static AssemblyLoaderProxy instance;
        protected AssemblyLoaderProxy() { }
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public object Loader { get; set; }
        public static AssemblyLoaderProxy Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new AssemblyLoaderProxy();
                }
                return instance;
            }
        }
        public Action<object> CompletedCallback
        {
            get
            {
                if (!IsAvailable)
                    return null;
                return (Action<object>)Loader.GetValue("CompletedCallback");
            }
            set
            {
                if (!IsAvailable)
                    return;
                Loader.SetValue("CompletedCallback", value);
            }
        }
        public Action<double> ProgressChangedCallback
        {
            get
            {
                if (!IsAvailable)
                    return null;
                return (Action<double>)Loader.GetValue("ProgressChangedCallback");
            }
            set
            {
                if (!IsAvailable)
                    return;
                Loader.SetValue("ProgressChangedCallback", value);
            }
        }
        public bool IsAvailable { get { return Loader != null; } }
        public bool CanLoadAssembly(string name)
        {
            if (!IsAvailable)
                return false;
            MethodInfo methodInfo = Loader.GetType().GetMethod("CanLoadAssembly");
            return (bool)methodInfo.Invoke(Loader, new object[] { name });
        }
        public void LoadAssembly(string name)
        {
            if (!IsAvailable)
                return;
            MethodInfo methodInfo = Loader.GetType().GetMethod("LoadAssembly");
            methodInfo.Invoke(Loader, new object[] { name });
        }
    }
}
